using System;

namespace BReusable
{
	/* http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx
	 * 
	 * XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Barry"),
                        new XElement("lastName", "Gottshall")
                    ),
                    new XElement("contact", 
                        new XAttribute("contactId", "3"),
                        new XElement("firstName", "Armando"),
                        new XElement("lastName", "Valdes")
                    )
                );
 
 
		Console.WriteLine(xml);
	 * 
	 */

	public static class XmlExtensions
	{
		/// <summary>
		/// From BReusable
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="input"></param>
		/// <returns></returns>
		public static string ToXmlString<T>(this T input)
		{
			using (var writer = new System.IO.StringWriter())
			{
				input.ToXml(writer);
				return writer.ToString();
			}
		}

		/// <summary>
		/// From BReusable
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="objectToSerialize"></param>
		/// <param name="stream"></param>
		public static void ToXml<T>(this T objectToSerialize, System.IO.Stream stream)
		{
			new System.Xml.Serialization.XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize);
		}

		/// <summary>
		/// From BReusable
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="objectToSerialize"></param>
		/// <param name="writer"></param>
		public static void ToXml<T>(this T objectToSerialize, System.IO.StringWriter writer)
		{
			new System.Xml.Serialization.XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
		}

		/// <summary>
		/// From BReusable
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="serialString"></param>
		/// <returns></returns>
		public static T Deserialize<T>(this String serialString)
		{
			System.IO.StringReader sr = new System.IO.StringReader(serialString);
			//var reader=new System.IO.MemoryStream(Stringstream serialString.);
			var result = new System.Xml.Serialization.XmlSerializer(typeof(T)).Deserialize(sr);
			if (result is T)
				return (T)result;
			return default(T);
		}
	}
}